package com.book.inaction.chapter1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @author tc
 * @date 2019/1/4
 */
public class ConnectExample {

    private static final Channel CHANNEL_FROM_SOMEWHERE = new NioSocketChannel();

    /**
     * Exception in thread "main" java.lang.IllegalStateException: channel not registered to an event loop
     * @param args
     */
    public static void main(String[] args) {
        Channel channel = CHANNEL_FROM_SOMEWHERE; //reference form somewhere

        // Does not block
        ChannelFuture future = channel.connect(
            new InetSocketAddress("127.0.0.1", 8899));

        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) {

                if (future.isSuccess()) {
                    ByteBuf buffer = Unpooled.copiedBuffer(
                        "Hello", Charset.defaultCharset());
                    ChannelFuture wf = future.channel()
                        .writeAndFlush(buffer);
                    // ...
                } else {
                    Throwable cause = future.cause();
                    cause.printStackTrace();
                }
            }
        });
    }

}
